"use client"
import React, { useEffect, useState } from "react";
import { useRouter } from 'next/navigation';
import { Button, Col, DatePicker, Form, Input, message, Modal, Row, Select, Space, Table, TableProps, Tag, Tooltip } from "antd";
import { DeleteOutlined } from "@ant-design/icons";
import { definitionStatus, start } from "@/clientApi/flowable/myProcess";
import useResponsiveLayout from "@/utils/useResponsiveLayout";
import { globalMessage } from "@/utils/message";
import RenderIconsCustom from "@/components/CustomIconSelector/conponents";
import { FormDto, getFormList } from "@/clientApi/flowable/form";
import { useConfirmModal } from "@/utils/ConfirmModal";


const formView: React.FC = () => {
        const { confirm } = useConfirmModal();
    const initialQueryParams = {
        pageNum: 1,
        pageSize: 10,
        name: null,


    };



    const navigateTo = useRouter();
    const [form] = Form.useForm();
    const [record, setRecord] = useState<Record<string, any>>({});
    const [forceUpdateKey, setForceUpdateKey] = useState(0); // 用于强制更新组件的 key
    const [dataList, setDataList] = useState<FormDto[]>([]);
    const columns: TableProps<FormDto>['columns'] = [
        {
            title: '表单ID',
            dataIndex: 'id',
            key: 'id',
            align: 'center',
            width: 80
        },
        {
            title: '表单名称',
            dataIndex: 'name',
            key: 'name',
            align: 'center',
            ellipsis: true,
            render: (text: string) => <a>{text}</a>
        },
        {
            title: '表单内容',
            dataIndex: 'formContent',
            key: 'formContent',
            align: 'center',
            ellipsis: true,
            render: (text: string) => (
                <Tooltip title={text}>
                    <span>{text ? text.substring(0, 20) + (text.length > 20 ? '...' : '') : '-'}</span>
                </Tooltip>
            )
        },
        {
            title: '创建人',
            dataIndex: 'createBy',
            key: 'createBy',
            align: 'center',
            render: (_, record) => (
                <Tag color="blue">{record.createBy}</Tag>
            )
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            align: 'center',
            sorter: true,
        },
        {
            title: '更新人',
            dataIndex: 'updateBy',
            key: 'updateBy',
            align: 'center',
            render: (text: number) => text || '-'
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            align: 'center',
            sorter: true,
        },
        {
            title: '备注',
            dataIndex: 'remark',
            key: 'remark',
            align: 'center',
            ellipsis: true,
            render: (text: string) => text || '-'
        }, {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            render: (_, record: any) => (
                <Space size="middle">
                    {record?.roleId !== 1 && (
                        <Tooltip title="设计">
                            <Button
                                type="link"
                                size="small"
                                icon={<RenderIconsCustom icon="edit" />}
                                onClick={() => EditClick(record)} />
                        </Tooltip>

                    )}
                    {record?.roleId !== 1 && (
                        <Tooltip title="删除">
                            <Button
                                type="link"
                                size="small"
                                icon={<DeleteOutlined />}
                                onClick={() => handleDelete(record)} />
                        </Tooltip>
                    )}

                </Space>
            ),
        },
    ];
    const [queryParams, setQueryParams] = useState(initialQueryParams);
    const [total, setTotal] = useState(0);
    const [openDataPermissions, setOpenDataPermissions] = useState<boolean>(false);
    useEffect(() => {
        getList();
    }, [queryParams]);  // 监听 queryParams 变化，调用 getList

    /** 查询用户列表 */
    function getList() {
        getFormList(queryParams).then((res: any) => {
            setDataList(res.rows.map((item: any) => ({
                ...item,
                // key: item.id // 使用 userId 作为唯一的 key
            })))
            setTotal(res.total); // 更新 total，用于分页
        });
    }

    // 查询列表
    function handleSearch() {
        form.validateFields().then(values => {
            console.log(values, 'values')
            setQueryParams(prevQueryParams => ({
                ...queryParams,
                name: values.name,
                "params[beginTime]": values.dateRange ? values.dateRange[0].format("YYYY-MM-DD") : null,
                "params[endTime]": values.dateRange ? values.dateRange[1].format("YYYY-MM-DD") : null,


            }));
        });
    }

    // 重置查询
    const resetSearch = () => {
        start("Process_1741856960558:1:e2145c96-ffea-11ef-b940-502b73101445").then((res: any) => {


        });
        // form.resetFields();
        // setQueryParams(initialQueryParams); // 重置为初始状态
    }

    // 分页变化
    const handleTableChange = (page: number, pageSize: number) => {
        setQueryParams({
            ...queryParams,
            pageNum: page,
            pageSize: pageSize,
        });
    };
    // 修改按钮
    const EditClick = (e: any) => {
        console.log("e", e)
        navigateTo.push(`/system/flowable/form/edit/${e.id}`)

    }
    // 删除按钮
    const handleDelete = (e: any) => {
        const roleIds = e.deploymentId;
        confirm({
            title: '系统提示',
            content: (`是否确认删除用户编号为"${roleIds}"的数据项？`),
            onOk() {
                // 用户点击“确定”按钮后执行的操作
                // definitionDelete(roleIds).then((res: any) => {
                //     if (res?.code === 200) {
                //          globalMessage().info("删除成功")
                //         getList()
                //     }
                // })
                // 在这里可以添加删除记录的逻辑
            },
            onCancel() {
                // 用户点击“取消”按钮后执行的操作

            },
        });

    }

    return (
        <div className='home'>
            <Row gutter={20} style={{ paddingTop: "20px" }}>
                <Col span={24}>
                    <div><Form
                        form={form}
                        name="definition_form_controls"
                        style={{ marginTop: 10, marginLeft: 10, marginBottom: 10 }}
                        layout={useResponsiveLayout("inline")}>
                        <Form.Item
                            name="name"
                            label="表单名称">
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="dateRange"
                            label="日期">
                            <DatePicker.RangePicker format="YYYY-MM-DD" />
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" onClick={handleSearch} style={{
                                marginRight: 20,
                            }}>
                                查询
                            </Button>
                            <Button type="primary" htmlType="reset" onClick={resetSearch}>
                                重置
                            </Button>
                        </Form.Item>
                    </Form></div>
                    <div><Button type="primary" ghost onClick={() => {
                        navigateTo.push(`/system/flowable/form/edit/add`)
                    }} style={{ margin: 10 }}>
                        新增
                    </Button></div>
                    <Table<FormDto> rowKey="id"
                        columns={columns}
                        dataSource={dataList}
                        scroll={{x:'max-content'}}
                        pagination={{
                            current: queryParams.pageNum,
                            pageSize: queryParams.pageSize,
                            total: total,

                            showSizeChanger: true, // 显示分页尺寸切换器
                            pageSizeOptions: ['10', '20', '50'], // 分页尺寸选项
                            onShowSizeChange: handleTableChange, // 分页尺寸变化时的回调
                            onChange: handleTableChange
                        }} />
                </Col>
            </Row>
        </div>
    )
};
export default formView;
